#!/bin/bash
# Copyright 2012 Google Inc.  All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License.  You may obtain a copy
# of the License at: http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distrib-
# uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
# specific language governing permissions and limitations under the License.

# Usage:
#
# tools/run [<options>]
#     Starts the App Engine dev server on the source directory (serving the
#     output of make) for local development and testing.  Serves on port 8000
#     by default, or the port specified in a file named DEFAULT_PORT located
#     in the same directory as app.yaml.  You can supply any additional
#     dev_appserver options, such as --port to override the default port.

pushd "$(dirname $0)" >/dev/null && source common.sh && popd >/dev/null

echo Serving from: $LOCAL_RUN_DIR
if [ -f $APPENGINE_DIR/devappserver2.py ]; then
  SERVER_VERSION=2
  SERVER_SCRIPT=devappserver2.py
  STORAGE_PATH=/tmp/devappserver2.$(basename $(pwd))
  DATASTORE_PATH=$STORAGE_PATH/datastore.db
else
  # In SDK 1.7.6, devappserver2.py got renamed to dev_appserver.py.
  if [ -f $APPENGINE_DIR/old_dev_appserver.py ]; then
    SERVER_VERSION=2
    SERVER_SCRIPT=dev_appserver.py
    STORAGE_PATH=/tmp/devappserver2.$(basename $(pwd))
    DATASTORE_PATH=$STORAGE_PATH/datastore.db
  else
    SERVER_VERSION=1
    SERVER_SCRIPT=dev_appserver.py
    DATASTORE_PATH=/tmp/devappserver.$(basename $(pwd))
  fi
fi

if [ -f $DATASTORE_PATH ]; then
  echo "Datastore at: $DATASTORE_PATH (exists)"
else
  echo "Datastore at: $DATASTORE_PATH (new)"
fi
echo

# Start the development appserver.
if [ $SERVER_VERSION == 2 ]; then
  $PYTHON $APPENGINE_DIR/$SERVER_SCRIPT \
      --storage_path $STORAGE_PATH \
      --admin_host 0.0.0.0 --admin_port $(($DEFAULT_PORT + 10)) \
      --port $DEFAULT_PORT --host 0.0.0.0 "$@" $LOCAL_RUN_DIR
else
  $PYTHON $APPENGINE_DIR/$SERVER_SCRIPT \
      --datastore_path $DATASTORE_PATH \
      --port $DEFAULT_PORT --address 0.0.0.0 "$@" $LOCAL_RUN_DIR
fi
